<template>
  <div>
    <el-form :inline="true" size="mini" ref="form">
      <el-form-item label="区域">
        <dx-cascader :area_id.sync="form.areaId" :area_name.sync="areaName" @change="handle_search" />
      </el-form-item>
      <el-form-item label="账期">
        <el-date-picker v-model="form.acctMonth" type="month" placeholder="选择帐期" :picker-options="pickerDisDate" value-format="yyyyMM" format="yyyy年MM月" @change="handle_search">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handle_search">查询</el-button>
        <el-button type="success" @click="handle_export">导出</el-button>
      </el-form-item>
    </el-form>

    <u-table ref="plxTable" class="tableBox" show-header-overflow="ellipsis" :height="height" stripe size="mini" :highlight-current-row="false" show-overflow :span-method="spanMethod"
      :cell-style="cellStyle" v-loading="loading">
      <u-table-column v-for="item in columns" :key="item.id" align="center" :prop="item.prop" :label="item.label" :minWidth="item.minWidth" :width="item.width" :fixed="item.fixed">
        <template v-slot="{ row, column }" v-if="item.slot">
          <span v-if="item.slot == 'value13'" :class="[renderUnderLine(row, column) && 'textUnderline',renderUnderLine(row, column) && 'color']"
            @click="renderUnderLine(row, column) && checkDialog(row,1)">
            {{ row[item.prop] }}
          </span>
          <span v-else @click="renderClass(row, column) && checkDialog(row)" :class="[renderClass(row, column) && 'textUnderline']">
            {{ row[item.prop] }}</span>
        </template>
        <template v-slot="{ row }" v-else>
          {{ row[item.prop] }}
        </template>
      </u-table-column>
    </u-table>

    <el-dialog :title="`费用详情 - ${dialogForm.acctMonth} - ${dialogForm.areaName}`" :visible.sync="dialogVisible" width="65%" @closed="handleClose">
      <u-table ref="plxTable2" show-header-overflow="ellipsis" stripe size="mini" class="tableBox" :highlight-current-row="false" show-overflow v-loading="dialogLoading">
        <u-table-column v-for="item in columns2" :key="item.id" align="center" show-overflow-tooltip :prop="item.prop" :label="item.label" show-overflow :minWidth="item.minWidth" :fixed="item.fixed">
        </u-table-column>
      </u-table>
      <!-- <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="mini">关闭</el-button>
      </span> -->
    </el-dialog>
  </div>
</template>

<script>
import { $budgetAPI } from "@/api";
import { downLoadExcelParams } from "@/utils/zipdownload";

export default {
  data() {
    return {
      areaName: "",
      disabledTime: "",
      form: {
        areaId: "",
        acctMonth: "",
      },
      columns: [],
      columns2: [],
      spanArr: [],

      loading: false,
      height: 0,
      pickerDisDate: {
        disabledDate: (time) => {
          let date = this.moment(this.disabledTime);
          let endDate = new Date(date);
          return time.getTime() > endDate.getTime();
        },
      },
      dialogVisible: false,
      dialogLoading: false,

      dialogType: "",
      dialogForm: {
        areaId: "",
        acctMonth: "",
        areaName: "",
      },
      formYear: "",
    };
  },
  mounted() {
    this.fetchMhGetMonth();
    this.getHeight();
    window.addEventListener("resize", this.getHeight);
  },
  methods: {
    getHeight() {
      this.height =
        window.innerHeight - this.$refs.form.$el.offsetHeight - 83 - 54 - 10;
    },
    handle_search() {
      this.fetchMonthTrack();
    },

    async fetchMhGetMonth() {
      let { content } = await this.fetch($budgetAPI.fetchMhGetMonth, {});
      this.form.acctMonth = content;
      this.disabledTime = content;
      this.handle_search();
    },

    async fetchMonthTrack() {
      this.loading = true;
      try {
        const { form } = this;
        let { content, code } = await this.fetch($budgetAPI.fetchMonthTrack, {
          ...form,
        });

        await this.$nextTick();
        if (code == 0) {
          this.formYear = form.acctMonth.slice(0, 4);
          this.columns = content.key.map((i, idx) => {
            return {
              label: content.name[idx],
              prop: i,
              resizable: true,
              slot: i.includes("value") ? i : undefined,
              width:
                (i == "displayName" && 80) ||
                (i == "value13" && 90) ||
                (i == "value14" && 100) ||
                (i.includes("value") && 70) ||
                (i == "hj" && 85) ||
                (i == "wcl" && 105),
              fixed: (i == "displayName" && "left") || undefined,
            };
          });
          // console.log(this.columns);
          this.$refs.plxTable.reloadData(
            content.data.map((item, index) => {
              let obj = { ...item };
              Object.keys(obj).forEach((i) => {
                if (obj[i] == 0) {
                  obj[i] = "";
                }
              });
              return obj;
            })
          );

          let contactDot = 0;
          let spanArr = [];

          content.data.forEach((item, index) => {
            if (index === 0) {
              spanArr.push(1);
            } else {
              if (item.displayName === content.data[index - 1].displayName) {
                spanArr[contactDot] += 1;
                spanArr.push(0);
              } else {
                contactDot = index;
                spanArr.push(1);
              }
            }
          });
          this.spanArr = spanArr;
        } else {
          this.$refs.plxTable.reloadData([]);
        }
      } finally {
        this.loading = false;
      }
    },
    handle_export() {
      const { form, areaName } = this;
      let fileName = `${areaName}-月度预算分解-${form.acctMonth}`;
      downLoadExcelParams("/mhTrack/monthExport", { ...form }, fileName);
    },
    renderClass(row, column) {
      for (let i = 1; i <= 12; i++) {
        let num = (i <= 9 && "0" + i) || i;
        if (
          row.value13 &&
          column.property == "value" + i &&
          row.cerateMonth == this.formYear + num &&
          row["value" + i]
        ) {
          return true;
        }
      }
    },

    renderUnderLine(row, column) {
      if (row.cerateMonth != "合计" && row.value13) {
        return true;
      }
    },

    cellStyle({ row, column, rowIndex, columnIndex }) {
      if (row.cerateMonth == "合计") {
        return { background: "#DEF3FD", color: "#000" };
      }
      for (let i = 1; i <= 12; i++) {
        let num = (i <= 9 && "0" + i) || i;
        if (
          row.value13 &&
          column.property == "value" + i &&
          row.cerateMonth == this.formYear + num &&
          row["value" + i]
        ) {
          return { background: "#4d9ef8", color: "#fff" };
        }
      }
    },
    spanMethod({ row, columnIndex, rowIndex }) {
      if (columnIndex === 0) {
        if (this.spanArr[rowIndex]) {
          return {
            rowspan: this.spanArr[rowIndex],
            colspan: 1,
          };
        } else {
          return {
            rowspan: 0,
            colspan: 0,
          };
        }
      } else if (columnIndex === 1) {
        if (row.cerateMonth.includes("备注")) {
          return {
            rowspan: 1,
            colspan: 18,
          };
        }
      }
    },
    checkDialog(row, type) {
      // console.log("row: ", row);

      this.dialogVisible = true;
      let form = {
        areaId: row.areaId,
        acctMonth: row.cerateMonth,
        areaName: row.displayName,
      };
      Object.assign(this.dialogForm, { ...form });
      this.dialogType = type;
      this.fetchCsTrack();
    },

    async fetchCsTrack() {
      let form = { ...this.dialogForm };
      let type = this.dialogType;

      this.dialogLoading = true;
      let actions =
        (type && $budgetAPI.fetchCsTrack) || $budgetAPI.fetchZqTrack;
      try {
        let { content, code } = await this.fetch(actions, {
          ...form,
        });

        if (code == 0) {
          this.columns2 = content.key.map((i, idx) => {
            return {
              label: content.name[idx],
              prop: i,
              minWidth: "80px",
            };
          });

          this.$refs.plxTable2.reloadData(
            content.data.map((item, index) => {
              let obj = { ...item };
              Object.keys(obj).forEach((i) => {
                if (obj[i] == 0) {
                  obj[i] = "";
                }
              });
              return obj;
            })
          );
        } else {
          this.$refs.plxTable2.reloadData([]);
        }
      } finally {
        this.dialogLoading = false;
      }
    },
    handleClose() {
      this.columns2 = [];
      this.dialogType = "";
      this.dialogForm = {
        acctMonth: "",
        areaId: "",
        areaName: "",
      };
      this.$refs.plxTable2.reloadData([]);
    },
  },
};
</script>

<style scoped lang="scss">
.textUnderline {
  font-weight: 900;
  cursor: pointer;
  text-decoration: underline;
  &.color {
    color: #4d9ef8;
  }
}
</style>
